package Java.ReadWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


//资源类
class MyCache {


    //创建map
    private volatile Map<String, Object> map = new HashMap<>();

    //创建读写锁对象
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //放数据
    public void put(String key, Object value) {
        //添加写锁
        readWriteLock.writeLock().lock();

        //暂停一会
        try {
            System.out.println(Thread.currentThread().getName() + "正在进行写操作" + key);
            TimeUnit.MICROSECONDS.sleep(300);

            //放数据
            map.put(key, value);


            System.out.println(Thread.currentThread().getName() + "写完了" + key);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放写锁
            readWriteLock.writeLock().unlock();
        }


    }


    //取方法
    public Object get(String key) {

        //添加毒素哦
        readWriteLock.readLock().lock();
        Object result = null;
        try {

            System.out.println(Thread.currentThread().getName() + "正在进行读取" + key);
            TimeUnit.MICROSECONDS.sleep(300);

            result = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完了" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }


        return result;
    }

}

public class ReadWriteLockDemo {


    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        //创建线程放数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.put(num + "", num + "");
            }, String.valueOf(i)).start();
        }


        //创建线程读数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.get(num + "");
            }, String.valueOf(i)).start();
        }

    }

}
